package cn.hesion.leetcode;

class LinkNode {
    Integer val;
    LinkNode next;
    LinkNode() {

    }
    LinkNode(int val) {
        this.val = val;
        this.next = null;
    }
}

class MyLinkedList {
    LinkNode dummyHead;
    int len;

    public MyLinkedList() {
        len = 0;
        dummyHead = new LinkNode();
    }

    public int get(int index) {
        LinkNode now = this.dummyHead;
        for (int i = 0; i <= index; i++) {
            now = now.next;
            if(now ==null){
                return -1;
            }
        }
        return now.val;
    }

    public void addAtHead(int val) {
        LinkNode newNode = new LinkNode(val);
        newNode.next = this.dummyHead.next;
        this.dummyHead.next = newNode;
        ++len;
    }

    public void addAtTail(int val) {
        LinkNode newNode = new LinkNode(val);
        LinkNode now = this.dummyHead;
        while (now.next != null){
            now = now.next;
        }
        now.next = newNode;
        ++len;
    }

    public void addAtIndex(int index, int val) {
        LinkNode newNode = new LinkNode(val);
        LinkNode now = this.dummyHead;
        if(index < 0){
            addAtHead(val);
            return;
        }
        if(index==len){
            addAtTail(val);
            return;
        }

        for (int i = 0; i < index; i++) {
            now = now.next;
            if(now ==null){
                return;
            }
        }
        LinkNode nnext = now.next;
        now.next = newNode;
        newNode.next = nnext;
        ++len;
    }

    public void deleteAtIndex(int index) {
        if(get(index) == -1){
            return;
        }
        LinkNode now = this.dummyHead;
        for (int i = 0; i < index; i++) {
            now = now.next;
        }
        now.next = now.next.next;
        --len;
    }

    public static void main(String[] args) {
        MyLinkedList linkedList = new MyLinkedList();
        linkedList.addAtHead(1);
        linkedList.addAtTail(3);
        linkedList.addAtIndex(1,2);   //链表变为1-> 2-> 3
        System.out.println(linkedList.get(1));            //返回2
        linkedList.deleteAtIndex(1);  //现在链表是1-> 3
        System.out.println(linkedList.get(1));            //返回3
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */